<template>
  <div class="system-user-list">
    <header class="header">
      <div class="search-section">
        <el-select v-model="roleId" placeholder="选择角色" @change="handleRoleChange" clearable>
          <el-option
            v-for="role in roleList"
            :key="role.F_role_id"
            :label="role.F_role_name"
            :value="role.F_role_id"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="input"
          placeholder="请输入姓名/手机号查询"
          prefix-icon="el-icon-search"
          maxlength="15"
          @input="inputChange"
          clearable
        ></el-input>
      </div>
      <div class="btn-group">
        <ButtonPermission code="systemUser:add" mode="disable">
          <template #default="{ disabled }">
            <el-button 
              type="primary" 
              icon="el-icon-plus" 
              :disabled="disabled"
              @click="!disabled && addUser()"
            >
              新增用户
            </el-button>
          </template>
        </ButtonPermission>
      </div>
    </header>
    <main class="main table-container">
      <div class="table-wrapper">
        <el-table ref="userTable" :data="userList" stripe border @data-updated="handleDataUpdated" class="responsive-table">
          <el-empty
            v-if="!loading && userList.length === 0"
            description="暂无数据"
            :image-size="100"
          ></el-empty>
          <el-table-column
            v-for="{ prop, label, width } in columnList"
            :key="prop"
            :label="label"
            :prop="prop"
            :min-width="width"
            align="center"
          >
            <template #default="scope">
              <template v-if="prop === 'F_roles'">
                <p v-for="{ F_role_name, F_id } in scope.row.F_roles" :key="F_id">
                  {{ F_role_name }}
                </p>
              </template>
              <template v-else-if="prop === 'F_disable'">
                <div class="switch-wrapper">
                  <span class="switch-text">{{
                    scope.row.F_disable === 1 ? '禁用' : '启用'
                  }}</span>
                  <el-switch
                    v-model="scope.row.F_disable"
                    :active-value="0"
                    :inactive-value="1"
                    active-color="#009cff"
                    inactive-color="#e7e7e7"
                    @change="(val) => toSwitch(scope.$index, val)"
                    style="margin-left: 8px;"
                  />
                </div>
              </template>
              <template v-else-if="prop === 'operation'">
                <ButtonPermission code="systemUser:edit" mode="disable">
                  <template #default="{ disabled }">
                    <span class="btn" :class="{ disabled: disabled }" @click="!disabled && editUser(scope.row)">编辑</span>
                  </template>
                </ButtonPermission>
                <ButtonPermission code="systemUser:delete" mode="disable">
                  <template #default="{ disabled }">
                    <span class="btn" :class="{ disabled: disabled }" @click="!disabled && deleteUser(scope.$index, scope.row)">删除</span>
                  </template>
                </ButtonPermission>
              </template>
              <template v-else>
                <p>{{ scope.row[prop] }}</p>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="table-footer">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="userTotal"
          :page-size="pageSize"
          @current-change="changePage"
          v-model:current-page="page"
        >
        </el-pagination>
      </div>
    </main>
    
    <!-- 新增/编辑用户弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="900px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleDialogClose"
      @opened="handleDialogOpened"
    >
      <div class="dialog-content" v-loading="formLoading">
        <!-- 编辑模式下显示创建时间 -->
        <div class="dialog-header-info" v-if="isEditMode && formData.createTime">
          <span class="create-time">添加时间：{{ formData.createTime }}</span>
        </div>
        <div class="block">
          <!-- <div class="title">用户信息</div> -->
          <div class="row">
            <div class="item role-name">
              <div class="label">
                <i>*</i>
                姓名
              </div>
              <div class="data">
                <el-input v-model="formData.F_user_name" maxlength="15"></el-input>
              </div>
            </div>
            <div class="item">
              <div class="label">
                <i>*</i>
                电话
              </div>
              <div class="data">
                <el-input v-model="formData.F_user_account" @input="handlePhoneInput"></el-input>
              </div>
            </div>
            <div class="item gender-item">
              <div class="label">
                <i>*</i>
                性别
              </div>
              <div class="data">
                <el-select v-model="formData.F_user_gender">
                  <el-option
                    v-for="item in genderList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
            </div>
            <div class="item">
              <div class="label">所属单位</div>
              <div class="data">
                <el-input v-model="formData.F_employer" maxlength="15"></el-input>
              </div>
            </div>
            <div class="item role-item">
              <div class="label">
                <i>*</i>
                角色
              </div>
              <div class="data">
                <el-select
                  v-model="formData.checkedRoleList"
                  multiple
                  collapse-tags
                  placeholder="请选择角色"
                  value-key="F_role_id"
                >
                  <el-option
                    v-for="role in [...formRoleList, ...hideRoleList]"
                    :key="role.F_role_id"
                    :label="role.F_role_name"
                    :value="role"
                  ></el-option>
                </el-select>
              </div>
            </div>
            <div class="item">
              <div class="label">账号</div>
              <div class="data">
                <el-input v-model="formData.F_account" maxlength="20"></el-input>
              </div>
            </div>
            <div class="item reset-pwd" style="width: 300px">
            <div class="label">密码</div>
            <div class="data" style="display: flex">
              <el-input
                v-model="password"
                maxlength="18"
                :disabled="pwdInputDisabled"
                :type="isEditMode && pwdInputDisabled ? (isShowPwd ? 'text' : 'password') : 'text'"
              ></el-input>
              <div
                class="reset-btn"
                v-if="pwdInputDisabled"
                @click="resetPassword"
              >
                重置
              </div>
              <div v-else @click="editPwd" class="reset-btn confirm-edit">
                保存
              </div>
              <i
                class="el-icon-view"
                @click="togglePwdShow"
                v-if="pwdInputDisabled"
              ></i>
            </div>
          </div>
          </div>
        </div>
        <set-range 
          ref="setRange" 
          :type="isEditMode ? 1 : 0" 
          :checkedRoleList="formData.checkedRoleList"
        ></set-range>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="formLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from '@/utils/utils';
import { mapGetters } from 'vuex';
import setRange from '@/components/systemManage/setRange.vue';
import { subjectList } from '@/utils/maps';

const INIT_SHOW_PWD = '******';

export default {
  name: 'SystemUserList',
  components: {
    setRange
  },
  data() {
    return {
      roleList: [],
      roleId: '',
      input: '',
      page: 1,
      pageSize: 20,
      userList: [],
      userTotal: 0,
      loading: false,
      columnList: [
        { prop: 'F_user_name', label: '姓名', width: '120' },
        { prop: 'F_user_account', label: '手机号', width: '150' },
        { prop: 'F_roles', label: '角色', width: '150' },
        { prop: 'F_disable', label: '状态', width: '120' },
        { prop: 'operation', label: '操作', width: '150' }
      ],
      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增用户',
      isEditMode: false,
      formLoading: false,
      genderList: [],
      formRoleList: [], // 表单中使用的角色列表（不包含"全部角色"）
      formData: {
        F_user_id: '',
        F_user_name: '',
        F_user_account: '',
        F_user_gender: 1,
        F_employer: '',
        F_account: '',
        checkedRoleList: [],
        createTime: '' // 编辑模式下的创建时间
      },
      hideRoleList: [], // 编辑时不在当前角色列表中的角色
      password: INIT_SHOW_PWD,
      pwdInputDisabled: true,
      isShowPwd: false
    };
  },
  computed: {
    ...mapGetters('user', ['isSuperAdmin', 'userPermission']),
    canManage() {
      return this.isSuperAdmin || this.userPermission.level < 4;
    }
  },
  async mounted() {
    // 确保按钮权限数据已加载
    await this.ensureButtonPermissionsLoaded();
    
    this.genderList = this.$maps.genderList;
    await this.getSysRoles();
    this.getSystemUsers();
  },
  watch: {
    '$route': {
      handler(to, from) {
        if (to.name === 'systemUserList') {
          this.getSystemUsers();
        }
      },
      immediate: true
    }
  },
  methods: {
    handleRoleChange() {
      this.page = 1; // 切换角色时重置页码
      this.getSystemUsers();
    },
    async getSysRoles() {
      try {
        // 使用新接口从rb_system_role表获取非学校角色（F_is_school_role=0）
        const { F_role_list } = await this.$api.getNonSchoolRoles();
        if (F_role_list && Array.isArray(F_role_list)) {
          // 数据格式转换：将后端返回的字段名转换为前端使用的字段名
          const allRoles = F_role_list
            .filter((e) => {
              // 过滤已删除的角色
              const isdel = e.isdel?.Int64 !== undefined ? e.isdel.Int64 : (e.F_isdel?.Int64 !== undefined ? e.F_isdel.Int64 : e.isdel || e.F_isdel || 0);
              return isdel === 0;
            })
            .map((role) => {
              // 统一字段名，确保兼容性
              // 注意：后端SystemRole结构体的Id字段JSON序列化为F_id
              const roleId = role.F_id || role.id || role.F_role_id;
              // 确保角色ID有效
              if (!roleId && roleId !== 0) {
                return null;
              }
              return {
                F_role_id: roleId,
                F_role_name: role.F_role_name || role.role_name || '',
                F_role_code: role.F_role_code || role.role_code || '',
                F_role_type: role.F_role_type !== undefined ? role.F_role_type : (role.role_type !== undefined ? role.role_type : (role.F_role_type?.Int64 !== undefined ? role.F_role_type.Int64 : role.role_type)),
                F_disable: role.F_disable !== undefined ? role.F_disable : (role.disable !== undefined ? role.disable : role.F_disable),
                F_isdel: role.F_isdel !== undefined ? role.F_isdel : (role.isdel !== undefined ? role.isdel : role.F_isdel),
                F_describe: role.F_describe || role.describe || '',
                F_is_school_role: role.F_is_school_role !== undefined ? role.F_is_school_role : (role.is_school_role !== undefined ? role.is_school_role : (role.F_is_school_role?.Int64 !== undefined ? role.F_is_school_role.Int64 : role.is_school_role)),
              };
            })
            .filter(role => role !== null); // 过滤掉无效的角色
          
          // 用于筛选的角色列表（包含"全部角色"）
          this.roleList = [{ F_role_id: '', F_role_name: '全部角色' }, ...allRoles];
          // 用于表单选择的角色列表（不包含"全部角色"）
          this.formRoleList = allRoles;
        } else {
          this.roleList = [{ F_role_id: '', F_role_name: '全部角色' }];
          this.formRoleList = [];
        }
      } catch (error) {
        console.error('获取角色失败:', error);
        this.roleList = [{ F_role_id: '', F_role_name: '全部角色' }];
        this.formRoleList = [];
      }
    },
    async getSystemUsers() {
      if (this.loading) return;
      this.loading = true;
      try {
        // 构建请求参数，过滤掉空值
        const params = {
          F_page: this.page,
          F_limit: this.pageSize
        };
        
        // 只有当 input 有值时才添加 F_name 参数
        if (this.input && this.input.trim() !== '') {
          params.F_name = this.input.trim();
        }
        
        // 只有当 roleId 有有效值时才添加 F_role_id 参数
        if (this.roleId && this.roleId !== '' && this.roleId !== null && this.roleId !== undefined) {
          params.F_role_id = this.roleId;
        }
        
        // 添加区域字段 F_district（从 userPermission 中获取）
        if (this.userPermission) {
          // 构建区域信息对象，格式与后端期望的一致
          const districtInfo = {
            province_list: this.userPermission.province_list || [],
            city_list: this.userPermission.city_list || [],
            county_list: this.userPermission.county_list || [],
            level: this.userPermission.level || 0,
            subject_list: this.userPermission.subject_list || [],
            stage: this.userPermission.stage || null
          };
          // 转换为 JSON 字符串
          params.F_district = JSON.stringify(districtInfo);
        }
        
        const { F_user_list, F_page_info: { F_total } } = await this.$api.getSystemUsers(params);
        this.userList = F_user_list;
        this.userTotal = F_total;
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$toast('获取用户列表失败');
      } finally {
        this.loading = false;
        this.$nextTick(() => {
          if (this.$refs.userTable) {
            this.$refs.userTable.doLayout();
          }
        });
      }
    },
    handleDataUpdated() {
      this.$refs.userTable?.doLayout();
    },
    inputChange() {
      var _this = this;
      debounce(function () {
        _this.getSystemUsers();
      }, 500);
    },
    changePage(page) {
      this.page = page;
      this.getSystemUsers();
    },
    async toSwitch(index, newStatus) {
      // newStatus 是 switch 的新值 (0 或 1)
      // 0 表示启用，1 表示禁用
      const F_user_id = this.userList[index].F_user_id;
      const oldStatus = this.userList[index].F_disable;
      // 先更新 UI（v-model 已经自动更新了，但为了确保，我们显式设置）
      this.userList[index].F_disable = newStatus;
      const formData = new FormData();
      formData.append('F_user_id', F_user_id);
      formData.append('F_status', newStatus);
      try {
        const { F_responseMsg, F_responseNo } = await this.$api.disableUser(
          formData
        );
        if (F_responseNo !== 10000) {
          this.$toast(
            `${newStatus === 0 ? '启用' : '禁用'}失败:${F_responseMsg}`,
            1000
          );
          // 失败时恢复原值
          this.userList[index].F_disable = oldStatus;
        }
      } catch (err) {
        console.error(err);
        this.$toast(`${newStatus === 0 ? '启用' : '禁用'}失败`, 1000);
        // 失败时恢复原值
        this.userList[index].F_disable = oldStatus;
      }
    },
    // 确保按钮权限数据已加载
    async ensureButtonPermissionsLoaded() {
      const menuTree = this.$store.state.user.menuTree || [];
      // 查找系统管理菜单
      const findMenu = (menus, targetName) => {
        for (const menu of menus) {
          const menuPath = menu.menu_path || '';
          if (menuPath) {
            const pathParts = menuPath.split('/').filter(part => part && part !== 'homepage');
            if (pathParts.length > 0 && pathParts[pathParts.length - 1] === targetName) {
              return menu;
            }
          }
          if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
            const found = findMenu(menu.children, targetName);
            if (found) return found;
          }
        }
        return null;
      };
      
      const systemManageMenu = findMenu(menuTree, 'systemManage');
      if (systemManageMenu && systemManageMenu.id) {
        // 检查是否已有按钮数据（menu_type === 2）
        const hasButtons = systemManageMenu.children && 
                          Array.isArray(systemManageMenu.children) && 
                          systemManageMenu.children.some(child => child.menu_type === 2);
        
        if (!hasButtons) {
          console.log('SystemUserList: 按钮权限数据不存在，开始获取，菜单ID:', systemManageMenu.id);
          try {
            // 登录时已经通过 fetchAllButtonPermissions 获取了完整的菜单树（包含所有子菜单和按钮）
            // 所以这里不需要再调用额外的 API
            console.log('SystemUserList: 按钮权限数据已在登录时加载完成');
          } catch (error) {
            console.error('SystemUserList: 处理按钮权限数据失败:', error);
          }
        } else {
          console.log('SystemUserList: 按钮权限数据已存在');
        }
      }
    },
    deleteUser(index, item) {
      if (!this.canManage) {
        this.$toast('您没有权限进行此操作');
        return;
      }
      const { F_user_id, F_user_name, F_type } = item;
      this.$delete(F_user_name, async () => {
        try {
          // 使用 deleteUserNew API，传递对象参数
          // 系统用户的类型是 7 或 8，优先使用 item 中的 F_type，如果没有则使用 8
          const { F_responseNo, F_responseMsg } = await this.$api.deleteUserNew({
            F_user_id,
            F_user_type: F_type || 8,
          });
          if (F_responseNo === 10000) {
            this.$toast('删除该用户成功');
            // 如果删除的是当前页第一项，且当前页是最后一页，则跳转到上一页
            if (
              index === 0 &&
              this.userTotal % this.pageSize === 1 &&
              this.userTotal !== 1 &&
              this.page === Math.ceil(this.userTotal / this.pageSize)
            ) {
              this.page = this.page - 1;
            }
            this.getSystemUsers();
          } else {
            this.$toast(`删除该用户失败: ${F_responseMsg}`);
          }
        } catch (error) {
          console.error(error);
          this.$toast('删除该用户失败');
        }
      });
    },
    addUser() {
      if (!this.canManage) {
        this.$toast('您没有权限进行此操作');
        return;
      }

      // 先清空 sessionStorage，确保不会预填充任何数据
      sessionStorage.removeItem('edit_system_user_info');
      
      this.isEditMode = false;
      this.dialogTitle = '新增用户';
      
      // 重置表单数据 - 确保所有字段都是空值，密码默认为123456
      this.formData = {
        F_user_id: '',
        F_user_name: '',
        F_user_account: '',
        F_user_gender: 1,
        F_employer: '',
        F_account: '',
        checkedRoleList: [],
        createTime: ''
      };
      this.password = '123456';
      this.pwdInputDisabled = false;
      this.isShowPwd = false;
      this.hideRoleList = [];
      
      // 清除 sessionStorage 中的编辑信息，确保新增模式
      sessionStorage.removeItem('edit_system_user_info');
      
      // 使用 nextTick 确保数据更新后再打开弹窗
      this.$nextTick(() => {
        // 再次确保所有字段都是空的
        this.formData.F_user_name = '';
        this.formData.F_user_account = '';
        this.formData.F_employer = '';
        this.formData.F_account = '';
        this.formData.checkedRoleList = [];
        this.password = '123456';
        this.dialogVisible = true;
      });
    },
    editUser(item) {
      if (!this.canManage) {
        this.$toast('您没有权限进行此操作');
        return;
      }

      this.isEditMode = true;
      this.dialogTitle = '编辑用户';
      
      // 填充表单数据
      const {
        F_user_id,
        F_user_name,
        F_user_account,
        F_gender,
        F_employer,
        F_roles,
        F_account,
        F_passwd
      } = item;
      
      this.formData.F_user_id = F_user_id;
      this.formData.F_user_name = F_user_name;
      this.formData.F_user_account = F_user_account;
      // 设置性别值（不自动转换，使用原始值）
      this.formData.F_user_gender = F_gender;
      this.formData.F_employer = F_employer || '';
      this.formData.F_account = F_account || '';
      // 设置密码：如果后端返回了原始密码，保存到 sessionStorage 供切换显示使用
      // 密码字段初始显示为占位符
      this.password = INIT_SHOW_PWD;
      this.pwdInputDisabled = true;
      this.isShowPwd = false;
      
      // 保存原始密码到 sessionStorage，供 togglePwdShow 使用
      if (F_passwd && F_passwd !== '') {
        // 更新 sessionStorage 中的密码信息
        const editUserInfo = JSON.parse(sessionStorage.getItem('edit_system_user_info') || '{}');
        editUserInfo.F_passwd = F_passwd;
        sessionStorage.setItem('edit_system_user_info', JSON.stringify(editUserInfo));
      }
      
      // 设置创建时间
      const { F_create_datetime } = item;
      this.formData.createTime = F_create_datetime || '';
      
      // 处理角色列表
      this.formData.checkedRoleList = [];
      this.hideRoleList = [];
      
      if (F_roles && Array.isArray(F_roles)) {
        F_roles.forEach((e) => {
          const roleId = String(e.F_id || e.F_role_id || '');
          const matchedRole = this.formRoleList.find((u) => {
            const uRoleId = String(u.F_role_id || '');
            return uRoleId === roleId || uRoleId === String(Number(roleId)) || String(Number(uRoleId)) === roleId;
          });
          if (matchedRole) {
            this.formData.checkedRoleList.push(matchedRole);
          } else {
            // 不在当前角色列表中的角色
            this.hideRoleList.push({
              F_role_id: e.F_id || e.F_role_id,
              F_role_name: e.F_role_name || e.RoleName,
              F_role_code: e.F_role_code || e.RoleCode,
              F_role_type: e.F_role_type || e.RoleType,
              F_disable: e.F_disable || e.Disable,
              F_isdel: e.F_isdel || e.Isdel,
              F_describe: e.F_describe || e.Describe,
              F_is_school_role: e.F_is_school_role || e.IsSchoolRole,
            });
          }
        });
      }
      
      // 临时保存到 sessionStorage，供 setRange 组件使用
      // setRange 组件会从 sessionStorage 读取编辑用户信息来设置区域信息
      // 注意：必须在设置 dialogVisible 之前设置 sessionStorage，这样 setRange 组件的 watch 才能正确读取数据
      sessionStorage.setItem('edit_system_user_info', JSON.stringify(item));
      
      this.dialogVisible = true;
    },
    // 处理弹窗打开后
    handleDialogOpened() {
      // 如果是新增模式，确保所有字段都是空的
      if (!this.isEditMode) {
        this.$nextTick(() => {
          // 强制重置表单数据，确保没有任何预填充，密码默认为123456
          this.formData = {
            F_user_id: '',
            F_user_name: '',
            F_user_account: '',
            F_user_gender: 1,
            F_employer: '',
            F_account: '',
            checkedRoleList: [],
            createTime: ''
          };
          this.password = '123456';
          this.pwdInputDisabled = false;
          this.isShowPwd = false;
          this.hideRoleList = [];
          // 再次清空 sessionStorage
          sessionStorage.removeItem('edit_system_user_info');
          // 新增模式，需要初始化数据范围组件
          if (this.$refs.setRange) {
            this.$refs.setRange.getNewDistrict();
            this.$refs.setRange.getAccountDistrict();
          }
        });
      } else {
        // 编辑模式下，确保 setRange 组件正确加载数据范围
        // 由于 setRange 组件的 watch 会在 type 变化时自动调用 getNewDistrict，
        // 但为了确保数据正确加载，我们在弹窗打开后再次触发
        this.$nextTick(async () => {
          if (this.$refs.setRange) {
            // 确保 accountDistrict 已加载
            await this.$refs.setRange.getAccountDistrict();
            // 手动触发 setRange 组件的数据范围更新
            this.$refs.setRange.getNewDistrict();
          }
        });
      }
    },
    
    // 处理弹窗关闭
    handleDialogClose() {
      this.dialogVisible = false;
      // 清理 sessionStorage
      sessionStorage.removeItem('edit_system_user_info');
      // 延迟重置表单，避免关闭动画时看到数据清空
      setTimeout(() => {
        this.resetFormData();
      }, 300);
    },
    
    // 重置表单数据
    resetFormData() {
      this.formData = {
        F_user_id: '',
        F_user_name: '',
        F_user_account: '',
        F_user_gender: 1,
        F_employer: '',
        F_account: '',
        checkedRoleList: [],
        createTime: ''
      };
      this.password = INIT_SHOW_PWD;
      this.pwdInputDisabled = true;
      this.isShowPwd = false;
      this.hideRoleList = [];
      this.isEditMode = false;
    },
    
    // 处理手机号输入
    handlePhoneInput(v) {
      this.formData.F_user_account = v.replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
      if (this.formData.F_user_account.length > 11) {
        this.formData.F_user_account = this.formData.F_user_account.slice(0, 11);
      }
    },
    
    // 切换密码显示/隐藏
    togglePwdShow() {
      const userInfo = JSON.parse(sessionStorage.getItem('edit_system_user_info') || '{}');
      const { F_passwd } = userInfo;
      this.password = this.isShowPwd ? INIT_SHOW_PWD : F_passwd;
      this.isShowPwd = !this.isShowPwd;
    },
    
    // 重置密码
    resetPassword() {
      this.password = '123456';
      this.pwdInputDisabled = false;
    },
    
    // 修改密码
    async editPwd() {
      try {
        const params = {
          F_update_user_id: this.formData.F_user_id,
          F_phone: this.formData.F_user_account,
          F_password: this.password,
        };
        const formData = new FormData();
        for (const [k, v] of Object.entries(params)) {
          formData.append(k, v);
        }
        const { F_responseNo, F_responseMsg } = await this.$api.editUserPW(formData);
        if (F_responseNo !== 10000) {
          this.$toast('修改密码失败:', F_responseMsg);
        } else {
          this.$toast('修改密码成功');
          // 更新 sessionStorage 中的密码
          const editUserInfo = JSON.parse(sessionStorage.getItem('edit_system_user_info') || '{}');
          editUserInfo.F_passwd = this.password;
          sessionStorage.setItem('edit_system_user_info', JSON.stringify(editUserInfo));
          // 恢复显示状态
          this.password = INIT_SHOW_PWD;
          this.pwdInputDisabled = true;
          this.isShowPwd = false;
        }
      } catch (e) {
        console.error(e);
        this.$toast('修改密码失败，请联系后台成员');
      }
    },
    
    // 表单验证
    checkFormData() {
      // 验证姓名
      if (!this.formData.F_user_name || this.formData.F_user_name.trim().length === 0) {
        this.$toast('请输入姓名');
        return false;
      }
      
      // 验证电话
      if (!this.formData.F_user_account || this.formData.F_user_account.length === 0) {
        this.$toast('请输入电话');
        return false;
      }
      if (this.formData.F_user_account.length !== 11) {
        this.$toast('请输入正确的11位手机号');
        return false;
      }
      
      // 验证性别
      if (this.formData.F_user_gender === undefined || this.formData.F_user_gender === null) {
        this.$toast('请选择性别');
        return false;
      }
      
      // 验证角色
      if (!this.formData.checkedRoleList || this.formData.checkedRoleList.length === 0) {
        this.$toast('请至少选择一个角色');
        return false;
      }
      
      // 验证密码（新增时必填）
      if (!this.isEditMode) {
        if (!this.password || this.password.trim() === '') {
          this.$toast('请输入密码');
          return false;
        }
        if (this.password.length < 6) {
          this.$toast('密码长度不能少于6位');
          return false;
        }
      }
      // 编辑模式下，如果密码输入框已启用（用户点击了重置后），需要验证密码
      if (this.isEditMode && !this.pwdInputDisabled) {
        if (!this.password || this.password.trim() === '' || this.password === INIT_SHOW_PWD) {
          this.$toast('请输入新密码');
          return false;
        }
        if (this.password.length < 6) {
          this.$toast('密码长度不能少于6位');
          return false;
        }
      }
      
      return true;
    },
    
    // 确认提交
    async handleConfirm() {
      if (!this.checkFormData()) {
        return;
      }
      
      this.formLoading = true;
      try {
        const isUpdate = this.isEditMode;
        
        // 获取角色ID列表和角色代码列表
        const roleIdList = this.formData.checkedRoleList.map(role => role.F_role_id);
        const roleCodeList = this.formData.checkedRoleList.map(role => role.F_role_code);
        
        // 获取数据范围
        let districtInfo = '';
        if (this.$refs.setRange) {
          const newDistrict = this.$refs.setRange.newDistrict;
          if (newDistrict) {
            const district = {
              province_list: newDistrict.province_list || [],
              city_list: newDistrict.city_list || [],
              county_list: newDistrict.county_list || [],
              level: newDistrict.level !== undefined ? newDistrict.level : 0,
              subject_list: newDistrict.subject_list || [],
              stage: newDistrict.stage !== undefined ? newDistrict.stage : null
            };
            districtInfo = JSON.stringify(district);
          }
        }
        
        if (!districtInfo) {
          districtInfo = JSON.stringify({
            province_list: [],
            city_list: [],
            county_list: [],
            level: 0,
            subject_list: [],
            stage: null
          });
        }

        // 构建请求参数
        const params = {
          F_user_id: isUpdate ? this.formData.F_user_id : '',
          F_user_name: this.formData.F_user_name || '',
          F_user_account: this.formData.F_user_account || '',
          F_user_gender: this.formData.F_user_gender !== undefined && this.formData.F_user_gender !== null ? this.formData.F_user_gender : 0,
          F_employer: this.formData.F_employer || '',
          F_role_ids: roleIdList.length > 0 ? JSON.stringify(roleIdList) : '',
          F_role_codes: roleCodeList.length > 0 ? JSON.stringify(roleCodeList) : '',
          F_account: this.formData.F_account || '',
          F_passwd: isUpdate ? (this.password !== INIT_SHOW_PWD && this.password ? this.password : '') : (this.password || ''),
          F_is_school_user: 0, // 系统用户
          F_district: districtInfo,
          F_school_id: '0',
        };
        
        if (!roleCodeList || roleCodeList.length === 0) {
          this.$toast('请至少选择一个角色');
          this.formLoading = false;
          return;
        }
        
        const { F_responseNo, F_responseMsg } = await this.$api.createOrUpdateUser(params, isUpdate);
        
        if (F_responseNo === 10000) {
          this.$toast(`${this.dialogTitle}成功`);
          // 关闭对话框并重置表单
          this.dialogVisible = false;
          this.resetFormData();
          // 刷新列表
          this.getSystemUsers();
        } else {
          this.$toast(`${this.dialogTitle}失败。${F_responseMsg}`, true);
        }
      } catch (e) {
        console.error(e);
        this.$toast(`${this.dialogTitle}失败`);
      } finally {
        this.formLoading = false;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.system-user-list {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: #fff;
    margin-bottom: 20px;

    .search-section {
      display: flex;
      gap: 10px;
      align-items: center;

      .el-select {
        width: 150px;
      }

      .el-input {
        width: 200px;
      }
    }
    
    .btn-group {
      display: flex;
      gap: 10px;
    }
  }

  .main {
    flex: 1;
    overflow: auto;
    background: #fff;
    padding: 20px;

    .table-wrapper {
      min-height: 400px;
    }

    .table-footer {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
  
  .dialog-content {
    padding: 10px 0;
    
    .dialog-header-info {
      margin-bottom: 24px;
      padding-bottom: 12px;
      border-bottom: 1px solid #e4e7ed;
      
      .create-time {
        color: #909399;
        font-size: 13px;
      }
    }
    
    .block {
      margin-bottom: 24px;
      
      .title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 20px;
        color: #303133;
        padding-left: 4px;
        border-left: 3px solid #409eff;
      }
      
      .row {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        
        .item {
          flex: 0 0 calc(33.333% - 14px);
          min-width: 200px;
          
          &.role-name {
            flex: 0 0 calc(25% - 15px);
          }
          
          &.gender-item {
            flex: 0 0 calc(25% - 15px);
          }
          
          &.role-item {
            flex: 0 0 calc(50% - 10px);
          }
          
          &.password-item {
            flex: 0 0 calc(50% - 10px);
          }
          
          .label {
            margin-bottom: 8px;
            color: #606266;
            font-size: 14px;
            font-weight: 500;
            display: flex;
            align-items: center;
            
            i {
              color: #f56c6c;
              margin-right: 4px;
              font-style: normal;
            }
          }
          
          .data {
            .el-input,
            .el-select {
              width: 100%;
            }
            
          }
          
          &.reset-pwd {
            .data {
              .el-input {
                flex: 1;
              }
              
              .reset-btn {
                font-size: 14px;
                width: 70px;
                height: 40px;
                line-height: 40px;
                text-align: center;
                color: #009cff;
                background-color: #f1efef;
                border-radius: 0 4px 4px 0;
                cursor: pointer;
                flex-shrink: 0;
              }
              
              .confirm-edit {
                color: #009cff;
                background-color: #fff;
                border: 1px solid #ccc;
              }
              
              i {
                width: 20px;
                height: 20px;
                cursor: pointer;
                color: #909399;
                font-size: 16px;
                margin-left: 8px;
                transition: color 0.3s;
                flex-shrink: 0;
                
                &:hover {
                  color: #409eff;
                }
              }
            }
          }
        }
      }
    }
  }
  
  // 优化对话框样式
  :deep(.el-dialog) {
    border-radius: 8px;
    
    .el-dialog__header {
      padding: 20px 24px 16px;
      border-bottom: 1px solid #e4e7ed;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .el-dialog__body {
      padding: 24px;
      max-height: 70vh;
      overflow-y: auto;
    }
    
    .el-dialog__footer {
      padding: 16px 24px;
      border-top: 1px solid #e4e7ed;
      
      .dialog-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        
        .el-button {
          min-width: 80px;
          padding: 10px 20px;
        }
      }
    }
  }

  .switch-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    
    .switch-text {
      margin-right: 8px;
    }
  }
  
  .btn {
    color: #409eff;
    cursor: pointer;
    margin: 0 5px;
    
    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
    
    &:hover:not(.disabled) {
      color: #66b1ff;
    }
  }
}
</style>